<?php
/**
 *
 * @author Strawberry🍓
 * @date 2021-05-26 4:05 下午
 *
 */

namespace app\api\controller;


use app\admin\model\AuthGroups;
use app\admin\model\AuthRuleWechat;
use app\api\service\JinDie;
use app\api\service\JwtService;
use app\common\energyApi\Energy;
use app\common\model\tang\Cost;
use app\common\model\tang\KwhWaterLog;
use app\common\model\tang\Merchant as MerchantModel;
use app\common\model\tang\MerchantLog;
use app\common\model\tang\MerchantReadingLog;
use app\common\model\tang\MonthElectricityDegree;
use app\common\model\tang\MonthElectricityRecord;
use app\common\model\tang\MonthSoleElectricityLog;
use app\common\model\tang\MonthWaterLog;
use app\common\model\tang\ReleaseRecord;
use app\common\model\tang\ReleaseUser;
use app\common\model\tang\Task;
use app\common\model\tang\WatchLog;
use app\common\model\tang\WatchMaintain;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class Release extends Base
{
//    public function login()
//    {
//        $code = $this->request->param('code');
//        $iv = $this->request->param('iv');
//        $encryptedData = $this->request->param('encryptedData');
//        if (empty($code) || empty($iv) || empty($encryptedData)) {
//            return SendError("参数错误");
//        }
//        $getUserInfo = $this->app->openPlatform->auth->session($code); //返回openid 和 sessionkey
//        if (!isset($getUserInfo['session_key']) || empty($getUserInfo['session_key'])) {
//            return SendError("code不不正确");
//        }
//        $decryptedData = $this->app->openPlatform->encryptor->decryptData($getUserInfo['session_key'], $iv, $encryptedData);
//        $mobile = $decryptedData['phoneNumber'];
////        $mobile = 15029080416;
//        // 小程序获取手机号的代码
//        $info = ReleaseUser::where(['mobile' => $mobile, 'status' => 1])->find();
//        if (empty($info)) {
////            return SendError("你不是安保人员无法登陆");
//            return SendError("你不是管理人员无法登陆");
//        }
//        //更新管理人员的openid
//        ReleaseUser::update(['openid'=>$getUserInfo['openid'],'unionid'=>$getUserInfo['unionid']],['id'=>$info['id']]);
//        $jwtAuth = JwtService::getInstance();
//        $token = $jwtAuth->setOpenid($getUserInfo['openid'])
//            ->setUid($info['id'])
//            ->setMobile($info['mobile'])
//            ->encode()
//            ->getToken();
//        return SendSuccess("登录成功", $token);
//    }


    /**
     *手机号授权登录
     */
    public function PhoneLogin()
    {
        $code = $this->request->param('code');
        $iv = $this->request->param('iv');
        $encryptedData = $this->request->param('encryptedData');
        if (empty($code) || empty($iv) || empty($encryptedData)) {
            return SendError("参数错误");
        }
        $getUserInfo = $this->app->openPlatform->auth->session($code); //返回openid 和 sessionkey
        if (!isset($getUserInfo['session_key']) || empty($getUserInfo['session_key'])) {
            return SendError("code不不正确");
        }
        $decryptedData = $this->app->openPlatform->encryptor->decryptData($getUserInfo['session_key'], $iv, $encryptedData);
        $mobile = $decryptedData['phoneNumber'];
        // 小程序获取手机号的代码
        $info = ReleaseUser::where(['mobile' => $mobile, 'status' => 1])->find();
        if (empty($info)) {
            return SendError("你不是管理人员无法登陆");
        }
        //更新管理人员的openid
        ReleaseUser::update(['openid' => $getUserInfo['openid'], 'unionid' => $getUserInfo['unionid']], ['id' => $info['id']]);
        $jwtAuth = JwtService::getInstance();
        $token = $jwtAuth->setOpenid($getUserInfo['openid'])
            ->setUid($info['id'])
            ->setMobile($info['mobile'])
            ->encode()
            ->getToken();
        return SendSuccess("登录成功", $token);
    }

    public function login()
    {
        $openid = $this->request->param('openid');
        $account = $this->request->param('account');
        $password = $this->request->param('password');
        if (empty($account) || empty($password) || empty($openid)) {
            return SendError('账号密码不能为空');
        }
        $info = ReleaseUser::where(['mobile' => $account])->field('id,password,status')->find();
        if (empty($info)) {
            return SendError("该商管员不存在");
        }
        //TODO 检测密码是否正确
        if (md5($password) != $info['password']) {
            return SendError("密码错误");
        }
        if ($info['status'] == -1) {
            return SendError("账户已冻结，请联系管理员");
        }
        ReleaseUser::update(['openid' => $openid,], ['id' => $info['id']]);
        $merchantLog = (new MerchantLog())->where('openid', $openid)->find();
        if (empty($merchantLog)) {
            $log['openid'] = $openid;
            $log['username'] = $account;
            $log['password'] = $password;
            (new MerchantLog())->save($log);
        } else {
            $log['username'] = $account;
            $log['password'] = $password;
            (new MerchantLog())->update($log, ['id' => $merchantLog['id']]);
        }
        $jwtAuth = JwtService::getInstance();
        $token = $jwtAuth->setOpenid($openid)
            ->setUid($info['id'])
            ->setMobile($account)
            ->encode()
            ->getToken();
        return SendSuccess("登录成功", $token);
    }

    public function getReleaseUserInfo()
    {
        // 小程序获取手机号的代码
        $info = ReleaseUser::where(['mobile' => $this->mobile, 'status' => 1])->field('id,name,mobile,groups')->find();
        if (empty($info)) {
            return SendError("你不是管理人员无法登录");
        }
        //获取管理端登录的权限
        $group = new AuthGroups();
        $getGroup = $group->where('id', $info['groups'])->field('id,rules')->find();
        $ruleList = AuthRuleWechat::field('id,title,url,name,type')->select();
        $rule = explode(',', $getGroup['rules']);
        $management = [];
        foreach ($ruleList as $key => $item) {
            foreach ($rule as $k => $v) {
                if ($item['id'] == $v) {
                    $management[] = $item;
                }
            }
        }
        $info['permissions'] = $management;
        return SendSuccess("success", $info);
    }

    public function showIdGetUserInfo()
    {
        $mobile = $this->request->param('mobile');
        if (empty($mobile)) {
            return SendError("参数错误");
        }
        $info = Cost::with(['merchants'])
            ->where('mobile', '=', $mobile)
            ->order('id desc')
            ->field('id,add_user,username,mobile,merchant_id,id_card_positive,cost_type_id,id_card_negative,other_certificate,date_type,start_time,end_time,create_time')
            ->find();
        if (empty($info)) {
            return SendError("没有该人员信息");
        }
        if ($info['date_type'] == 1) {
            $info['date'] = '永久有效';
        } else {
            if ($info['start_time'] > time()) {
                return SendError("没有该人员信息");
            }
            if ($info['end_time'] < time()) {
                return SendError("通行证已过期");
            }
            $info['date'] = date('Y.m.d', $info['start_time']) . '-' . date('Y.m.d', $info['end_time']);
        }
        $info['id_card_positive'] = $info['id_card_positive'] ? $this->request->domain() . $info['id_card_positive'] : '';
        $info['id_card_negative'] = $info['id_card_negative'] ? $this->request->domain() . $info['id_card_negative'] : '';
        $info['other_certificate'] = $info['other_certificate'] ? $this->request->domain() . $info['other_certificate'] : '';
        $info['time'] = date('Y/m/d', $info['create_time']);
        return SendSuccess("success", $info);
    }
    /**
     * 获取商户上报任务列表
     */
    public function getMerchantTask(){
        $result = (new AuthRuleWechat())->where(['name'=>'ManageTrinity'])->select();
        if($result->isEmpty()){
            return SendSuccess('success',[]);
        }
        return SendSuccess('success',$result->toArray());
    }
    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException  获取商户列表
     */
    public function MerchantList()
    {
        $company_name = $this->request->param('name');
        if (empty($company_name)) {
            return SendError('请输入关键字搜索');
        }
        $result = MerchantModel::field('id,company,name,code,positions_code,biz_state')->where('code|name|company|username|positions_code', 'like', '%' . $company_name . '%')->select();
        if ($result->isEmpty()) {
            return SendSuccess('success', []);
        } else {
            $result = $result->toArray();
            foreach ($result as $ke => $ve) {
                if ($ve['biz_state'] == 'stopped') {
                    $result[$ke]['biz_state'] = '已停止';
                } else {
                    $result[$ke]['biz_state'] = '进行中';
                }
            }
            return SendSuccess('success', $result);
        }
    }

    /**
     *根据商户获取商户下水电表
     */
    public function getWatchList()
    {
        $merchant_id = $this->request->param('merchant_id');
        if (empty($merchant_id)) {
            return SendError('请传入商户id');
        }
        $result = MerchantModel::field('id,company,name,code,positions_code,biz_state')->where('id', $merchant_id)->find();
        $watchList = (new WatchMaintain())->with(['merchant'])->where(['merchant_id' => $merchant_id])->where('status', 1)->select();
        $data['merchantInfo'] = $result;
        if ($watchList->isEmpty()) {
            $data['watchInfo'] = [];
            return SendSuccess('success', $data);
        }
        $data['watchInfo'] = $watchList->toArray();
        return SendSuccess('success', $data);
    }
    public function getUpWatchList()
    {
        $merchant_id = $this->request->param('merchant_id');
        if (empty($merchant_id)) {
            return SendError('请传入商户id');
        }
        $result = MerchantModel::field('id,company,name,code,positions_code,biz_state')->where('id', $merchant_id)->find();
        $watchList = (new WatchMaintain())->with(['merchant'])->whereIn('type',[3,4])->where(['merchant_id' => $merchant_id])->where('status', 1)->select();
        $data['merchantInfo'] = $result;
        if ($watchList->isEmpty()) {
            $data['watchInfo'] = [];
            return SendSuccess('success', $data);
        }
        $data['watchInfo'] = $watchList->toArray();
        return SendSuccess('success', $data);
    }
    /**
     *表名称搜索表号
     */
    public function searchWatch()
    {
        $name = $this->request->param('name');
        if (empty($name)) {
            return SendError('请传入搜索内容');
        }
        $watchList = WatchMaintain::where('pointId|pointName', 'like', '%' . $name . '%')->where('status', 1)->where(['merchant_id'=>1918])->select();
        if ($watchList->isEmpty()) {
            return SendSuccess('success', []);
        }
        return SendSuccess('success', $watchList);
    }

    /**
     * 商户入离场抄表提交
     */
    public function submitWatch()
    {
        $param = $this->request->param();
        if (empty($param['pointId'])) {
            return SendError('请传入电表编号');
        }
        if ($param['in_type'] == 1 && empty($param['merchant_id'])) {
            return SendError('入场请选择商户');
        }
        $jin = new JinDie();//金蝶service
        $monthWaterLog = new MonthWaterLog();//水表记录
        $soleElectricityLog = new MonthSoleElectricityLog();//单一电表记录
        $monthElectricityLog = new MonthElectricityDegree();//费率电表记录
        $month = date('Y-m', strtotime(date('Y-m') . " - 1 month"));
        $param['dateTime'] = date('Y-m');
        $param['dateTimeLog'] = date('Y-m-d');
        Db::startTrans();
        try {
            if ($param['in_type'] == 2) { //说明离场
                //查表信息
                $watchInfo = (new WatchMaintain())->where(['pointId' => $param['pointId'],'merchant_id'=>$param['merchant_id']])->find();
                if (empty($watchInfo)) {
                    return SendError('表信息不存在或不属于这个商户');
                }
                if($watchInfo['type']==1){
                    $Energy = new Energy();
                    $watch= new WatchLog();
                    $data = [
                        "pointId" => $param['pointId'],
                        "operType" => 1 //1 拉闸2 合闸
                    ];
                    Log::info('商户离场拉闸请求数据:'.json_encode($data));
                    //查询月电费接口
                    $port_data = $Energy->universalfunction('remote_disconnect', $data);
                    if(empty($port_data)||$port_data==false){
                        $port_data = $Energy->universalfunction('remote_disconnect', $data);
                    }
                    if(isset($port_data)){
                        $watch->pointId = $data['pointId'];
                        $watch->operType = $data['operType'];
                        $watch->return_info = json_encode($port_data);
                        $watch->create_time = time();
                        $watch->save();
                    }
                }
                if ($watchInfo['type'] == 2 || $watchInfo['type'] == 4) { //说明是水表,智能水表有读数
                    $lastWater = $monthWaterLog->where(['pointId' => $param['pointId']])->order('create_time desc')->find();
                    if (empty($lastWater)) {
                        $monthdata = [
                            "water_or_electricity" => 1,
                            'type' => 3,
                            'day_month' => 3,
                            'pointId' => $watchInfo['point'],
                            'startdate' => $month,
                            'enddate' => ''
                        ];
                        $lastWater = $jin->getElectricity($monthdata);
                        if(empty($lastWater)){
                            $startBm = 0;
                        }else{
                            $startBm = $lastWater['endbm'];
                        }
                    } else {
                        $startBm = $lastWater['end'];
                    }
                    if($param['sole']<$startBm){
                        return SendError('单一水表不能低于上月末抄表');
                    }
                    $monthWaterLogData = [
                        'merchant_id' => $watchInfo['merchant_id'],
                        'pointId' => $param['pointId'],
                        'start' => $startBm,
                        'end' => $param['sole'],
                        'dataTime' => date('Y-m'),
                        'create_time' => time(),
                        'in_type' => $param['in_type'],
                        'use_type'=>$watchInfo['use_type']
                    ];
                    $saveInfo = $monthWaterLog->save($monthWaterLogData);
                    //解除绑定时候需要更换商户id,绑定到默认合同上去

                } else {
                    //电表 is_sole ==1 单一电表 否则为倍率用表
                    //单一表去查 单一表 tang_month_sole_electricity_log
                    if ($watchInfo['is_sole'] == 1) {
                        $lastSoleElectricityInfo = $soleElectricityLog->where(['pointId' => $param['pointId']])->order('create_time desc')->find();
                        if (empty($lastSoleElectricityInfo)) {
                            $dandata = [
                                "water_or_electricity" => 2,
                                'type' => 3,
                                'day_month' => 3,
                                'pointId' => $watchInfo['point'],
                                'startdate' => $month,
                                'enddate' => ''
                            ];
                            $EleInfo = $jin->getElectricity($dandata);
                            if(empty($EleInfo)){
                                $EleInfo = $jin->getElectricity($dandata);
                            }
                            $startBm =isset($EleInfo['endbm'])?$EleInfo['endbm']:0;
                        } else {
                            $startBm = $lastSoleElectricityInfo['zongEnd'];
                        }
                        if($param['sole']<$startBm){
                            return SendError('单一电表不能低于上月末抄表');
                        }
                        $monthWaterLogData = [
                            'merchant_id' => $watchInfo['merchant_id'],
                            'pointId' => $param['pointId'],
                            'pointName' => $watchInfo['pointName'],
                            'zongStart' => $startBm,
                            'zongEnd' => $param['sole'],
                            'totalPower' => bcmul(bcsub($param['sole'], $startBm, 2), $watchInfo['rate'], 2),
                            'dataTime' => date('Y-m'),
                            'create_time' => time(),
                            'in_type' => $param['in_type'],
                            'use_type'=>$watchInfo['use_type']
                        ];
                       $saveInfo = $soleElectricityLog->save($monthWaterLogData);
                    }else{ //sole不等于1 则是单一用表
                        $lastEleInfo = $monthElectricityLog->order('dataTime desc')->where(['pointId'=>$param['pointId']])->find();
                        if(empty($lastEleInfo)){
                            $dandata = [
                                "water_or_electricity" => 2,
                                'type' => 2,
                                'day_month' => 3,
                                'pointId' => $watchInfo['point'],
                                'startdate' => $month,
                                'enddate' => ''
                            ];
                            $EleInfo = $jin->getElectricity($dandata);
                            if(empty($EleInfo)){
                                $EleInfo = $jin->getElectricity($dandata);
                            }
                            $fengStart= isset($EleInfo['feng']['endbm'])?$EleInfo['feng']['endbm']:0;
                            $guStart= isset( $EleInfo['gu']['endbm'])? $EleInfo['gu']['endbm']:0;
                            $pingStart= isset( $EleInfo['ping']['endbm'])? $EleInfo['ping']['endbm']:0;
                        }else{
                            $fengStart= $lastEleInfo['fengEnd'];
                            $guStart= $lastEleInfo['guEnd'];
                            $pingStart= $lastEleInfo['pingEnd'];
                        }
                        if($param['fengpower']<$fengStart||$param['gupower']<$guStart||$param['pingpower']<$pingStart){
                            return SendError('抄表不能低于上月末结束值');
                        }
                        $EleInfoData=[
                            'merchant_id' => $watchInfo['merchant_id'],
                            'pointId' => $param['pointId'],
                            'pointName' => $watchInfo['pointName'],
                            'dataTime' => date('Y-m'),
                            'rate' => $watchInfo['rate'],
                            'fengStart' => $fengStart,
                            'fengEnd' => $param['fengpower'],
                            'fengPower' => bcmul(bcsub($param['fengpower'], $fengStart, 2), $watchInfo['rate'], 2),
                            'guStart' => $guStart,
                            'guEnd' =>$param['gupower'],
                            'guPower' => bcmul(bcsub($param['gupower'], $guStart, 2), $watchInfo['rate'], 2),
                            'pingStart' => $pingStart,
                            'pingEnd' => $param['pingpower'],
                            'pingPower' =>bcmul(bcsub($param['pingpower'], $pingStart, 2), $watchInfo['rate'], 2),
                            'create_time' => time(),
                            'in_type' => $param['in_type'],
                            'use_type'=>$watchInfo['use_type']
                        ];
                        $saveInfo = $monthElectricityLog->save($EleInfoData);
                    }
                }
                if($saveInfo){
                    $new_merchant_id = 1918;
                    $log = (new MerchantReadingLog())->where($param)->find();
//                    if($log){
//                        return SendError('请勿重复提交');
//                    }
//                    $watchInfo->where(['pointId' => $param['pointId']])->update(['merchant_id' => $new_merchant_id]);
                    $param['new_merchant_id'] = $new_merchant_id;
                    (new MerchantReadingLog())->save($param);
                    DB::commit();
                    return SendSuccess('解除成功', []);
                }
            }else{ //==1说明入场
                $watchInfo = (new WatchMaintain())->where(['pointId' => $param['pointId']])->find();
                if(empty($watchInfo)){
                    return SendError('电表不存在');
                }
                //离场商户是否确认,未确认新商户不能绑定
                $isconfirm = (new MerchantReadingLog)->order('create_time desc')->where(['pointId'=>$param['pointId'],'in_type'=>2])->find();
                if(isset($isconfirm)){
                    if($isconfirm['is_read']!=1){
                        return SendError('请联系退场商户确认,在进行绑定');
                    }
                }
                $isconfirmRu = (new MerchantReadingLog)->order('create_time desc')->where(['pointId'=>$param['pointId'],'in_type'=>1])->find();
                if(isset($isconfirmRu)){
                    if($isconfirmRu['is_read']!=1){
                        return SendError('请联系入场商户确认,在进行绑定');
                    }
                }
                if($param['merchant_id']==$watchInfo['merchant_id']){
                    return SendError('绑定商户不能相同');
                }
//                (new WatchMaintain())->where(['pointId' => $param['pointId']])->update(['merchant_id' => $param['merchant_id']]);
                $merchant_id = $param['merchant_id'];
                $param['merchant_id'] =  $watchInfo['merchant_id'];
                $param['new_merchant_id'] =  $merchant_id;
                (new MerchantReadingLog())->save($param);
                //若商户有余额,则触发合闸
                $merchant_balance = MerchantModel::where('id', $merchant_id)->value('balance');
                if($merchant_balance>0&&$watchInfo['type']==1){
                    $Energy = new Energy();
                    $watch= new WatchLog();
                    $data = [
                        "pointId" => $param['pointId'],
                        "operType" => 2 //1 拉闸2 合闸
                    ];
                    Log::info('商户入场合闸请求数据:'.json_encode($data));
                    // 查询月电费接口
                    $port_data = $Energy->universalfunction('remote_disconnect', $data);
                    if(empty($port_data)||$port_data==false){
                        $port_data = $Energy->universalfunction('remote_disconnect', $data);
                    }
                    if(isset($port_data)){
                        $watch->pointId = $data['pointId'];
                        $watch->operType = $data['operType'];
                        $watch->return_info = json_encode($port_data);
                        $watch->create_time = time();
                        $watch->save();
                    }
                }
                DB::commit();
                return SendSuccess('绑定成功', []);
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }

    /**
     * @return \think\response\Json  获取用户水电表,以及上次的度数,时间
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTableInfo()
    {
        $merchId = $this->request->param('merchant_id');
        $type = $this->request->param('type');
        if (empty($merchId) || !isset($merchId)) {
            return SendError("请传入正确的参数");
        }
        if (empty($type)) {
            return SendError("请传入正确的参数");
        }
        $table = WatchMaintain::where(['merchant_id' => $merchId, 'status' => 1])->where('type', $type)->field('id,pointId,pointName,type')->select();
        if (!$table->isEmpty()) {
            $table = $table->toArray();

            foreach ($table as $key => $val) {
                $info = [];
                if ($val['type'] == 3) {
                    $info = MonthSoleElectricityLog::where('pointId', $val['pointId'])->order('id desc')->find();
                    $table[$key]['last_electricity'] = isset($info['zongEnd']) ? $info['zongEnd'] : '0.00'; //上次用电
                    $table[$key]['type'] = $val['type']; //上次用电
                    $table[$key]['last_month'] = isset($info['dataTime']) ? $info['dataTime'] : date('Y-m');
                    $table[$key]['pointId'] = $val['pointId'];
                    $table[$key]['last_time'] = isset($info['create_time']) ? date('Y-m-d H:i:s', $info['create_time']) : 0;//上次记录时间
                    $table[$key]['new_time'] = date('Y-m-d H:i:s', time());//上次记录时间
                } else {
                    $info = MonthWaterLog::where('pointId', $val['pointId'])->order('id desc')->find();
                    $table[$key]['last_electricity'] = isset($info['end']) ? $info['end'] : '0.00'; //上次用电
                    $table[$key]['type'] = $val['type']; //上次用电
                    $table[$key]['pointId'] = $val['pointId'];
                    $table[$key]['last_month'] = isset($info['dataTime']) ? $info['dataTime'] : date('Y-m');
                    $table[$key]['last_time'] = isset($info['create_time']) ? date('Y-m-d H:i:s', $info['create_time']) : 0;//上次记录时间
                    $table[$key]['new_time'] = date('Y-m-d H:i:s', time());//上次记录时间
                }
            }
        }
        return SendSuccess('success', $table);
    }

    /**
     * @return \think\response\Json  商管提交抄表记录
     */
    public function upRecord()
    {
        $param = $this->request->param();
        if (empty($param['merchant_id'])||empty($param['type'])||empty($param['pointId'])) {
            return SendError("参数错误");
        }
        if(isset($param['now_electricity'])&&$param['now_electricity']==''){
            return SendError("请输入度数");
        }
        //获取上月号
//        $lastMonth = strtotime(date('Y-m') . " - 1 month");
        $lastMonth = date('Y-m', strtotime(date('Y-m') . " - 1 month"));
        Db::startTrans();
        try {
            $model = new MonthSoleElectricityLog(); //电费抄表
            $waterModel = new MonthWaterLog(); //水费抄表
            $code = (new MerchantModel())->where('id', $param['merchant_id'])->value('code');
            if ($param['type'] == 3) {
                $data = [];
                //查看商户是否有入厂
                $MerchantReadingLog = (new MerchantReadingLog())->where(['pointId' => $param['pointId'],'in_type'=>1])->find();
                $recordInfo = $model->where(['dataTime' => $lastMonth,'merchant_id' => $param['merchant_id'], 'pointId' => $param['pointId']])->find();
                $secondMonthInfo = $model->where(['pointId' => $param['pointId']])->order('dataTime desc')->find();
                $pointInfo = (new WatchMaintain())->where(['pointId' => $param['pointId']])->find();
                if ($recordInfo) return SendError('您已经抄过此商户表了');
                if(!empty($secondMonthInfo)){
                    if ($secondMonthInfo['zongEnd'] > $param['now_electricity']) return SendError('本次抄表不能低于上次抄表');
                }else{
                    if($pointInfo['initial_degrees']>0&&empty($secondMonthInfo)){
                        if ($pointInfo['initial_degrees'] > $param['now_electricity']) {
                            return SendError('本次抄表不能低于初始读数');
                        }else{
                            $secondMonthInfo['zongEnd'] = $pointInfo['initial_degrees'];
                        };
                    }else{
                        $secondMonthInfo['zongEnd'] = 0;
                    }

                }
                if(!empty($MerchantReadingLog)){
                    $secondMonthInfo['zongEnd'] =$MerchantReadingLog['sole'];
                }
                $data['dataTime'] = $lastMonth;
                $data['code'] = $code;
                $data['pointId'] = $param['pointId'];
                $data['merchant_id'] = $param['merchant_id'];
                $data['pointName'] = $pointInfo['pointName'];
                $data['rate'] = $pointInfo['rate'];
                $data['zongEnd'] = $param['now_electricity'];
                $data['zongStart'] = $secondMonthInfo['zongEnd'];
                $data['totalPower'] = bcmul(bcsub($param['now_electricity'], $secondMonthInfo['zongEnd'], 2), $pointInfo['rate'], 2);
                $data['create_time'] = time();
                $info = $model->save($data);
            } else {
                $data = [];
                //查看商户是否有入厂
                $MerchantReadingLog = (new MerchantReadingLog())->where(['pointId' => $param['pointId'],'in_type'=>1])->find();
                $recordInfo = $waterModel->where(['dataTime' => $lastMonth, 'merchant_id' => $param['merchant_id'],'pointId' => $param['pointId']])->find();
                $secondMonthInfo = $waterModel->where(['pointId' => $param['pointId']])->order('dataTime desc')->find();
                $pointInfo = (new WatchMaintain())->where(['pointId' => $param['pointId']])->find();
                if ($recordInfo) return SendError('您已经抄过此商户表了');
                if(!empty($secondMonthInfo)){
                    if ($secondMonthInfo['end'] > $param['now_electricity']) return SendError('本次抄表不能低于上次抄表');
                }else{
                    if($pointInfo['initial_degrees']>0&&empty($secondMonthInfo)){

                        if ($pointInfo['initial_degrees'] > $param['now_electricity']) {
                            return SendError('本次抄表不能低于初始读数');
                        }else{
                            $secondMonthInfo['end'] = $pointInfo['initial_degrees'];
                        };
                    }else{
                        $secondMonthInfo['end'] = 0;
                    }

                }
                if(!empty($MerchantReadingLog)){
                    $secondMonthInfo['end'] =$MerchantReadingLog['sole'];
                }
                $data['dataTime'] = $lastMonth;
                $data['merchant_id'] = $param['merchant_id'];
                $data['pointId'] = $pointInfo['pointId'];
                $data['pointName'] = $pointInfo['pointName'];
                $data['rate'] = $pointInfo['rate'];
                $data['end'] = $param['now_electricity'];
                $data['start'] = $secondMonthInfo['end'];
                $data['create_time'] = time();
                $info = $waterModel->save($data);
            }
            if ($info) {
                Db::commit();
                return SendSuccess("success", []);
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }

    /**
     * 管理获取商户账单
     */
    public function oweCost()
    {
        $merchant_id = $this->request->param('merchant_id');
        if (empty($merchant_id)) {
            return SendError('请传入商户id');
        }
        $list = Cost::where(['merchant_id' => $merchant_id, 'pay_status' => 0])
            ->with(['costType' => function ($e) {
                $e->field('id,cost_name,type')->find();
            }])
            ->order('id desc')
            ->field('id,type,amount,real_amount,create_time,cost_type_id,start_time,end_time,all_amount,pay_amount')
            ->select();
        if ($list->isEmpty()) {
            return SendSuccess("success", []);
        } else {
            $list = $list->toArray();
        }
        foreach ($list as $key => $value) {
            $list[$key]['amount'] = $value['amount'] / 100;
            $list[$key]['all_amount'] = $value['all_amount'] / 100;
            $list[$key]['pay_amount'] = $value['pay_amount'] / 100;
            $list[$key]['create_time'] = date('Y/m/d', strtotime($value['create_time']));
            $list[$key]['costType']['name'] = $list[$key]['costType']['cost_name'];
            if (!empty($value['start_time'])) {
                $list[$key]['start_time'] = date('Y/m/d', $value['start_time']);
            }
            if (!empty($value['end_time'])) {
                $list[$key]['end_time'] = date('Y/m/d', $value['end_time']);
            }
        }
        return SendSuccess("success", $list);
    }

    /**
     * 获取商管需要上报的列表
     */
    public function TaskList()
    {
        $result = ReleaseUser::where(['id' => $this->user_id])->find();
        if (empty($result)) {
            return SendError("该用户不存在");
        }
        $systemTask = Task::field('id as type,name')->where('type_staff', 2)->select()->toArray();
        return SendSuccess('success', $systemTask);
    }

    /**
     *通过task中type值,查询用户的组件
     */
    public function TaskDetail()
    {
        $id = $this->request->param('type');
        $TaskInfo = Task::field('id as type,name,text')->where('id', $id)->find();
        if (empty($TaskInfo)) {
            return SendError('任务详情不存在');
        } else {
            if (!empty($TaskInfo['text'])) {
                $TaskInfo['text'] = json_decode($TaskInfo['text'], true);
                $arrData = $TaskInfo['text'];
                foreach ($arrData as $k => $v) {
                    $arrData[$k]['image'] = '';
                    $arrData[$k]['value'] = '';
                }
                $TaskInfo['text'] = $arrData;
            }

        }
        return SendSuccess('success', $TaskInfo);
    }

    public function getIdByLog()
    {
        $status = $this->request->param('status');
        $user_id = $this->request->param('user_id');
        $mobile = $this->request->param('mobile');
        $merchant_id = $this->request->param('merchant_id');
        $merchant_sn = $this->request->param('merchant_sn');
        $certificate_type = $this->request->param('certificate_type');
        $username = $this->request->param('username');
        if (empty($user_id) || empty($merchant_id) || empty($certificate_type) || empty($merchant_sn) || empty($username)) {
            return SendError("参数错误");
        }
        $model = new ReleaseRecord();
        $model->merchant_sn = $merchant_sn;
        $model->release_user_id = $this->user_id;
        $model->certificate_type = $certificate_type;
        $model->username = $username;
        $model->mobile = $mobile;
        $model->user_mobile = $this->mobile;
        $model->status = $status;
        $info = $model->save();
        if (empty($info)) {
            return SendError("稍后再试");
        }
        return SendSuccess("success", $info);
    }


    public function getRecord()
    {
        $page = $this->request->param('page') ?? 1;
        $info = ReleaseRecord::page($page, 10)->order('id desc')->select();
        $count = ReleaseRecord::count();
        $total = ceil($count / 10);
        foreach ($info as $key => $value) {
            $info[$key]['time'] = date('Y/m/d', $value['create_time']);
        }
        return SendSuccess("success", compact('info', 'total'));
    }
}